﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LOGISTCBUS.Entities;
using LOGISTCBUS.DAO;

namespace LOGISTCBUS.WebUI.Controllers
{
    [HandleError(View = "Error")]
    public class UserController : Controller
    {
        public ActionResult Index()
        {
            var user = (User)this.Session["user"];
            if (user == null)
                return RedirectToAction(@"LogOut", @"Account");
            return View();
        }

        public ActionResult Edit(int? id)
        {
            var userLogged = (User)this.Session["user"];
            if (userLogged == null)
                return RedirectToAction(@"LogOut", @"Account");

            if (id.HasValue)
            {
                var user = new UserDAO().selectById(Convert.ToInt32(id));
                this.ViewData[@"user"] = user == null ? new User() : user;
            }

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Save(int id)
        {
            var u = id > 0 ? new UserDAO().selectById(id) : new User();
            var aux = true;

            if (!String.IsNullOrEmpty(Request.Params["name"]))
                u.Name = Request.Params["name"];
            if (!String.IsNullOrEmpty(Request.Params["email"]))
                u.Email = Request.Params["email"];
            if (!String.IsNullOrEmpty(Request.Params["login"]))
                u.Login = Request.Params["login"];
            if (!String.IsNullOrEmpty(Request.Params["password"]))
                u.Password = Encryption.EncryptMd5(Request.Params["password"]);
            if (!String.IsNullOrEmpty(Request.Params["id_city"]))
                u.City = new City() { Id = Convert.ToInt32(Request.Params["id_city"]) };
            if (!String.IsNullOrEmpty(Request.Params["description"]))
                u.Description = Request.Params["description"];

            if (u.Id > 0)
                aux = new UserDAO().update(u);
            else
                aux = new UserDAO().insert(u);

            var obj = new
            {
                success = aux,
                message = "Usuário salvo com sucesso!"
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Search()
        {
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var name = String.IsNullOrEmpty(Request.Params[@"name"]) ? string.Empty : Request.Params[@"name"].ToString();
            var pageSize = MvcApplication.pageSize;
            var users = new UserDAO().select(name, page, pageSize);
            var count = new UserDAO().getCount(name);
            var totalPages = (count < pageSize) ? 1 : Math.Ceiling(Convert.ToDecimal(count) / pageSize);
            var lst = new List<object>();

            foreach (var u in users)
            {
                var c = new CityDAO().selectById(u.City.Id);
                lst.Add(new
                {
                    Id = u.Id,
                    Name = u.Name,
                    Login = u.Login,
                    Email = u.Email,
                    City = c != null && c.Id > 0 ? c.FullName : string.Empty,
                });
            }

            var obj = new
            {
                data = lst,
                currpage = page,
                totalpages = totalPages,
                totalrecords = count
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete()
        {
            var id = String.IsNullOrEmpty(Request.Params[@"id"]) ? 0 : Convert.ToInt32(Request.Params[@"id"]);
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var aux = true;

            if (id > 0)
            {
                var u = new User() { Id = id };
                aux = new UserDAO().delete(u);
            }

            var obj = new
            {
                Message = "Registro removido com sucesso!",
                Success = aux,
                Page = page
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteAll()
        {
            var values = Request.Form["ids"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var aux = true;

            var lst = new List<User>();
            foreach (var val in values)
                if (!String.IsNullOrEmpty(val))
                    lst.Add(new User() { Id = Convert.ToInt32(val) });
            aux = new UserDAO().delete(lst);

            var obj = new
            {
                Message = "Registro(s) removido(s) com sucesso!",
                Success = aux
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult LoadCities()
        {
            var idState = String.IsNullOrEmpty(Request.Params[@"idState"]) ? 0 : Convert.ToInt32(Request.Params[@"idState"]);
            var lst = new List<object>();

            if (idState > 0)
            {
                var cities = new CityDAO().selectByState(idState);

                foreach (var c in cities)
                {
                    lst.Add(new
                    {
                        Id = c.Id,
                        Name = c.Name
                    });
                }
            }

            return Json(lst);
        }
    }
}
